package com.bitland.demo.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.bitland.demo.api.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 刘建文
 * @Date: Created in 11:53 2020/7/27
 * @Description: redis测试
 */
@RestController
@Slf4j
@RequestMapping(value = "/redis")
public class RedisController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    //测试地址 单服务测试地址  http://localhost:7010/provider/redis/employee/123
    // 网关测试地址  http://localhost:7050/gateway/apiprovider/provider/redis/employee/123
    @Cacheable(cacheNames ="cache:redis:getEmployee" , key = "#id")
    @GetMapping({"/employee/{id}"})
    public Employee getEmployee(@PathVariable("id") String id) {
        //模拟从数据库中查询
        Employee employee = new Employee();
        employee.setId("123");
        employee.setEmployeeNo("A000001");
        employee.setName("武松");
        return employee;
    }

    @CacheEvict(cacheNames ="cache:redis:getEmployee" , key = "#id")
    @DeleteMapping({"/employee/{id}"})
    //http://localhost:7010/provider/redis/employee/123
    public String deleteEmployee(@PathVariable("id") String id) {
        //@TODO 删除员工
        return "delete success";
    }
    /**
     * 用stringRedisTemplate，直接从 redis数据库中读出数据
     */
    @GetMapping({"/getDateByRedisTemplate"})
    //http://localhost:7010/provider/redis/getDateByRedisTemplate
    public String getDateByRedisTemplate() {
        Set<String> keys = stringRedisTemplate.keys("cache:redis:getEmployee::*");
        Object obj = null;
        for (String key : keys) {
            if (key != null) {
                obj = stringRedisTemplate.opsForValue().get(key);
                if (obj == null) {
                    continue;
                }
                System.out.println(obj.toString());
            }

        }
        return obj.toString();
    }

    @GetMapping({"/setDataTest/{key}/{value}"})
    //http://localhost:7010/provider/redis/setDataTest/name/志刚
    public String setData(@PathVariable("key")String key,@PathVariable("value")String value) {
        //向redis里存入数据和设置缓存时间
        stringRedisTemplate.opsForValue().set(key, value,60*10, TimeUnit.SECONDS);
        return "ok";
    }
}
